package com.huweilong.tingshu.servlet.album;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huweilong.tingshu.repository.TrackRepo;
import com.huweilong.tingshu.util.Log;
import com.huweilong.tingshu.view_object.CandidateTrackList;
import com.huweilong.tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 是阿秋啊
 * @date 2022/07/23 13:30
 **/
@WebServlet("/studio/album/candidate.json")
public class CandidateJsonServlet extends HttpServlet {
    private final CandidateTrackList candidateTrackList = new CandidateTrackList();
    private final TrackRepo trackRepo = new TrackRepo();
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String aid = req.getParameter("aid");
        UserVO currentUser = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            currentUser = (UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter writer = resp.getWriter();
        if (currentUser == null) {
            Log.println("UploadDoServlet用户未登录");
            resp.sendRedirect("/studio/user/login.html");
            return;
        }


        candidateTrackList.currentUser = currentUser;
        candidateTrackList.aid = aid;
        candidateTrackList.trackList = trackRepo.selectCandidateTrackByUidAndNotCand(currentUser.uid,aid);

        String json = objectMapper.writeValueAsString(candidateTrackList);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
        Log.println("传入响应体JSON");
    }
}